package com.wutuo.contact.provider.service;

import cn.apestar.agg.user.info.service.UserService;
import cn.apestar.core.http.AppType;
import cn.apestar.core.json.JsonConverter;
import cn.apestar.user.api.enums.UserType;
import cn.apestar.user.provider.info.domain.User;
import cn.apestar.user.provider.institution.domain.InstitutionSimpleVo;
import cn.apestar.user.provider.institution.request.InstitutionRequest;
import cn.apestar.user.provider.institution.response.InstitutionResponse;
import cn.apestar.user.provider.institution.service.InstitutionService;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.wutuo.child.api.response.ChildResponse;
import com.wutuo.child.provider.service.ChildService;
import com.wutuo.contact.api.ContactAPIService;
import com.wutuo.contact.provider.component.ContactDataConvert;
import com.wutuo.contact.provider.enums.ContactType;
import com.wutuo.contact.provider.vo.ContactListItem;
import com.wutuo.contact.provider.vo.ParentSiteContactListItem;
import com.wutuo.roster.api.request.ParentsRequest;
import com.wutuo.roster.api.request.SearchRosterRequest;
import com.wutuo.roster.api.response.ParentsResponse;
import com.wutuo.roster.provider.component.ParentUtil;
import com.wutuo.roster.provider.service.ParentsService;
import com.wutuo.roster.provider.service.RosterService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service public class ContactService implements ContactAPIService {

    @Autowired private ChildService childService;

    @Autowired private InstitutionService institutionService;

    @Autowired private ParentsService parentsService;

    @Autowired private RosterService rosterService;

    @Autowired private UserService userService;

    @Autowired private JsonConverter jsonConverter;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static List<Long> getInstitutionIds(List<ChildResponse> childInfos) {

        if (CollectionUtils.isEmpty(childInfos)) {
            return Collections.emptyList();
        }

        List<Long> institutionIds = new ArrayList<>();
        for (ChildResponse childResponse : childInfos) {
            if (childResponse.getCmInstitutionId() == null
                || childResponse.getCmInstitutionId() == 0) {
                continue;
            }
            institutionIds.add(childResponse.getCmInstitutionId());
        }
        return institutionIds;
    }

    public List<ContactListItem> getContactList(ContactType contactType, Long institutionId,
        Long userId) {

        UserType userType = UserType.get(contactType.getValue());
        List<User> users = userService.listUserByUserType(userType, institutionId);

        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }

        // 获取机构信息，同事列表机构信息一致
        InstitutionSimpleVo institutionSimpleVo = new InstitutionSimpleVo();
        if (institutionId != null && institutionId != 0) {
            InstitutionResponse institution = institutionService.getById(institutionId);
            institutionSimpleVo.setInstitutionId(institutionId);
            institutionSimpleVo.setImg(institution.getLogo());
            institutionSimpleVo.setName(institution.getInstitutionName());
        }

        List<ContactListItem> response = new ArrayList<>();
        for (User user : users) {
            if (user.getId() == null || user.getId().equals(userId)) {
                continue;
            }

            ContactListItem item = new ContactListItem();
            item.setId(user.getId());
            item.setImg(user.getPhoto());
            item.setName(user.getName());
            item.setPhone(user.getPhone());
            item.setRingId(user.getRingId());
            item.setSex(user.getSex());
            item.setType(user.getUserType());
            item.setInstitionInfo(institutionSimpleVo);
            response.add(item);
        }

        return response;
    }

    public List<ContactListItem> getParentList(Long institutionId, Long userId, String app) {

        ParentsRequest searchParentRequest = new ParentsRequest(institutionId);
        List<ParentsResponse> parents = parentsService.list(searchParentRequest);
        if (CollectionUtils.isEmpty(parents)) {
            return Collections.emptyList();
        }
        logger.info("parents size:{}", parents.size());

        List<Long> rosterIds = new ArrayList<>();
        for (ParentsResponse parent : parents) {
            if (parent.getRosterId() == null || parent.getRosterId() == 0) {
                continue;
            }
            rosterIds.add(parent.getRosterId());
        }

        // Get childs info
        SearchRosterRequest searchRosterRequest = new SearchRosterRequest();
        searchRosterRequest.setRosterIds(rosterIds);
        if (institutionId != null) {
            searchRosterRequest.setCmId(institutionId.toString());
        }
        List<ChildResponse> childs = rosterService.getChildListByPid(searchRosterRequest);
        Map<Long, ChildResponse> childsInfoMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(childs)) {
            for (ChildResponse child : childs) {
                childsInfoMap.put(child.getId(), child);
            }
        }

        // 获取机构信息，同事列表机构信息一致
        InstitutionSimpleVo institutionSimpleVo = new InstitutionSimpleVo();
        if (institutionId != null && institutionId != 0) {
            InstitutionResponse institution = institutionService.getById(institutionId);
            institutionSimpleVo.setInstitutionId(institutionId);
            institutionSimpleVo.setImg(institution.getLogo());
            institutionSimpleVo.setName(institution.getInstitutionName());
        }

        // Get user infos
        Set<String> phones = ParentUtil.getParentsAccountList(parents);
        Map<String, User> userInfoMap =
            userService.listUserByAccountsToPhone(phones, ContactType.PARENT.getValue());

        return ContactDataConvert
            .buildParentListResponse(parents, childsInfoMap, userInfoMap, userId,
                institutionSimpleVo);
    }

    public List<ContactListItem> getWorkmateList(Long institutionId, Long userId) {

        return getContactList(ContactType.WORKMATE, institutionId, userId);
    }

    /**
     * 家长端联系人列表
     *
     * @param userId
     * @return
     */
    public List<ParentSiteContactListItem> list(Long userId) {

        SearchRosterRequest request = new SearchRosterRequest();
        request.setParentId(userId);

        // 获取当前用户所关注的小孩
        List<ChildResponse> childInfos = rosterService.getChildListByPid(request);
        if (CollectionUtils.isEmpty(childInfos)) {
            return Collections.emptyList();
        }

        // 获取同时关注当前用户所关注小孩的家长列表
        List<Long> childIds = Lists.transform(childInfos, new Function<ChildResponse, Long>() {
            @Override public Long apply(ChildResponse input) {
                return input.getId();
            }
        });
        ParentsRequest searchParentReq = new ParentsRequest(StringUtils.join(childIds, ','));
        List<ParentsResponse> parentsInfo = parentsService.list(searchParentReq);

        // 获取孩子所在的所有机构的机构信息
        List<Long> institutionIds = getInstitutionIds(childInfos);
        InstitutionRequest searchInstitutionReq = new InstitutionRequest();
        searchInstitutionReq.setIncludeIds(institutionIds);
        List<InstitutionResponse> institutions =
            institutionService.list(searchInstitutionReq, false);

        // 获取机构的老师列表 TODO:需要做列表长度限制
        List<User> teachersInfo = userService.listUserByUserType(UserType.TEACHER, institutionIds);

        return buildListResponse(parentsInfo, institutions, teachersInfo);
    }

    public List<ParentSiteContactListItem> buildListResponse(List<ParentsResponse> parentsInfo,
        List<InstitutionResponse> institutions, List<User> teachersInfo) {

        List<ParentSiteContactListItem> result = new ArrayList<>();

        // 构建家长联系人信息
        this.buildParentContactList(result, parentsInfo);

        // 构建教师联系人信息
        this.buildTeacherContactList(result, institutions, teachersInfo);

        return result;
    }

    protected List<ParentSiteContactListItem> buildParentContactList(
        List<ParentSiteContactListItem> result, List<ParentsResponse> parentsInfo) {

        // 没有小孩信息就无需获取小孩对应机构下老师的信息
        if (CollectionUtils.isEmpty(parentsInfo)) {
            return Collections.emptyList();
        }

        ParentSiteContactListItem parentSiteContactList = new ParentSiteContactListItem();
        List<ContactListItem> parentInfoList = new ArrayList<>();
        parentSiteContactList.setCatlogName("家人");
        parentSiteContactList.setContacts(parentInfoList);

        // build child category
        for (ParentsResponse parentInfo : parentsInfo) {
            User user =
                userService.getUserByAccount(parentInfo.getUserPhone(), AppType.PARENT.getValue());
            ContactListItem item = new ContactListItem();
            item.setChildName(parentInfo.getUserName());
            if (user != null) {
                item.setId(user.getId());
                item.setImg(user.getPhoto());
                item.setSex(user.getSex());
                item.setPhone(user.getPhone());
                item.setRingId(user.getRingId());
            }
            item.setYear("");
            item.setType("parent");
            item.setName(parentInfo.getUserName());
            item.setInstitionInfo(new InstitutionSimpleVo()); // 家长部分不需要获取机构详情
            if (parentInfoList.contains(item)) {
                continue;   // 去重复
            }
            parentInfoList.add(item);
        }

        result.add(parentSiteContactList);

        return result;
    }

    protected void buildTeacherContactList(List<ParentSiteContactListItem> result,
        List<InstitutionResponse> institutions, List<User> teachersInfo) {
        // build teacher category
        if (CollectionUtils.isEmpty(institutions)) {
            return;
        }

        for (InstitutionResponse institution : institutions) {
            if (institution.getId() == null) {
                continue;
            }

            InstitutionSimpleVo institutionSimpleVo = new InstitutionSimpleVo();
            institutionSimpleVo.setInstitutionId(institution.getId());
            institutionSimpleVo.setImg(institution.getLogo());
            institutionSimpleVo.setName(institution.getInstitutionName());

            List<ContactListItem> contactListItems = new ArrayList<>();

            ParentSiteContactListItem record = new ParentSiteContactListItem();
            record.setCatlogName(institution.getInstitutionName());
            record.setContacts(contactListItems);
            for (User teacher : teachersInfo) {
                if (teacher.getInstitutionId() == null || !institution.getId()
                    .equals(teacher.getInstitutionId())) {
                    continue;
                }
                ContactListItem item = new ContactListItem();
                item.setChildName(StringUtils.EMPTY);
                item.setName(teacher.getName());
                item.setId(teacher.getId());
                item.setParentType(StringUtils.EMPTY);
                item.setImg(teacher.getPhoto());
                item.setPhone(teacher.getAccount());
                item.setRingId(teacher.getRingId());
                item.setInstitionInfo(institutionSimpleVo);
                item.setSex(teacher.getSex());
                item.setType(teacher.getUserType());
                item.setYear(StringUtils.EMPTY);
                contactListItems.add(item);
            }

            result.add(record);
        }
    }
}
